import sqlite3
import threading
from contextlib import contextmanager

class DatabaseManager:
    _instance = None
    _lock = threading.Lock()
    _local = threading.local()

    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super(DatabaseManager, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        self.db_path = None

    def init_app(self, db_path):
        self.db_path = db_path

    def get_db_path(self):
        return self.db_path

    def get_db(self):
        if not hasattr(self._local, 'db'):
            self._local.db = sqlite3.connect(
                self.db_path,
                detect_types=sqlite3.PARSE_DECLTYPES
            )
            self._local.db.row_factory = sqlite3.Row
        return self._local.db

    def close_db(self):
        if hasattr(self._local, 'db'):
            self._local.db.close()
            del self._local.db

    @contextmanager
    def get_connection(self):
        try:
            db = self.get_db()
            yield db
        finally:
            self.close_db()

    def init_db(self):
        with self.get_connection() as db:
            # 设置时区
            db.execute("PRAGMA timezone = 'localtime'")
            db.execute("PRAGMA journal_mode = WAL")
            db.execute("PRAGMA synchronous = NORMAL")
            
            # 创建用户表
            db.execute('''
                CREATE TABLE IF NOT EXISTS users (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    username TEXT UNIQUE NOT NULL,
                    password TEXT NOT NULL
                )
            ''')
            # 创建同步目录表
            db.execute('''
                CREATE TABLE IF NOT EXISTS sync_dirs (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id INTEGER NOT NULL,
                    local_path TEXT NOT NULL,
                    ftp_host TEXT NOT NULL,
                    ftp_user TEXT NOT NULL,
                    ftp_pass TEXT NOT NULL,
                    ftp_path TEXT NOT NULL,
                    sync_status TEXT DEFAULT 'idle',
                    last_sync TIMESTAMP,
                    sync_strategy TEXT DEFAULT 'time_size',
                    FOREIGN KEY (user_id) REFERENCES users (id)
                )
            ''')
            # 创建同步历史表
            db.execute('''
                CREATE TABLE IF NOT EXISTS sync_history (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    sync_dir_id INTEGER NOT NULL,
                    filename TEXT NOT NULL,
                    direction TEXT NOT NULL,
                    operation TEXT NOT NULL,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    path TEXT NOT NULL,
                    FOREIGN KEY (sync_dir_id) REFERENCES sync_dirs (id)
                )
            ''')
            db.commit()

db_manager = DatabaseManager() 